<!DOCTYPE html>
<html lang="zh-cn">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JS014-随机点名案例</title>
</head>
<style>
  body {
    background-color: #333;
    color: snow;
  }

  h2 {
    text-align: center;
  }

  .display-name {
    text-align: center;
    color: pink;
  }

  .control-panel {
    display: flex;
    justify-content: center;
    gap: 0.5rem;
  }
</style>

<body>
  <h2>JS014-随机点名案例</h2>
  <h3 class="display-name">.display-name</h3>
  <div class="control-panel">
    <button class="start-btn">开始</button>
    <button class="stop-btn" disabled>停止</button>
  </div>
  <script>
    /**
     * 1 开始按钮：随机滚动名字
     * 2 停止按钮：停止滚动名字
     * 3 已经点到的名字从列表中删除
     */
    const displayName = document.querySelector('.display-name')
    const startBtn = document.querySelector('.start-btn')
    const stopBtn = document.querySelector('.stop-btn')
    const names = [
      'witw', 'systerror', '为霜', '霸气的三石',
      'api', '傲慢的小肉包', 'kaofish', 'longbaobao',
      '12dora', '逍遥散人M', '机智的肯尼'
    ]

    startBtn.addEventListener('click', startRandom)
    stopBtn.addEventListener('click', stopRandom)

    let randomTimerId = -1
    let selectedIndex = -1

    function startRandom() {
      if (names.length <= 0) {
        displayName.innerHTML = '没有名字了'
        startBtn.disabled = true
        stopBtn.disabled = true
        return
      }

      startBtn.disabled = true
      stopBtn.disabled = false

      randomTimerId = setInterval(function () {
        displayName.innerHTML = getRandomName(names)
      }, 50)
    }

    function stopRandom() {
      startBtn.disabled = false
      stopBtn.disabled = true

      clearInterval(randomTimerId)
      names.splice(selectedIndex, 1)
    }

    function getRandomName(names) {
      selectedIndex = getRandom(0, names.length - 1)
      return names[selectedIndex]
    }

    function getRandom(m, n) {
      return Math.floor(Math.random() * (n - m + 1)) + m
    }
  </script>
</body>

</html>